<!--时间管理-->
<script setup lang="ts">
import {
  getTimeProjectForm,
  getTimeProjectPage,
  addTimeProject,
  updateTimeProject,
  deleteTimeProject,
  addTimeProjectOptions,
  getTimeProjectOptions,
  updateTimeProjectOptions,
  deleteTimeProjectOptions,
  updateTimeProjectPercentage,
  updateTimeProjectProportion,
} from "@/api/time/project";

import {
  TimeProjectPageQuery,
  TimeProjectPageResult,
  TimeProjectPageVO,
  TimeProjectForm,
  TimeItemProjectForm,
} from "@/api/time/types";

import { TimeProjectTypeEnum } from "@/enums/TimeProjectTypeEnum";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const dataItemFormRef = ref(ElForm);

const loading = ref(false);
const loadingItem = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<TimeProjectPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const timeProjectList = ref<TimeProjectPageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const dialogItem = reactive({
  title: "",
  visible: false,
  projectId: 0,
});

const formData = reactive<TimeProjectForm>({
  status: 1,
});

const formDataItem = reactive<TimeItemProjectForm>({
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: "请输入时间管理名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入时间管理编码", trigger: "blur" }],
});

// 选择表格的行菜单ID
const selectedRowMenuId = ref<number | undefined>();

/** 查询 */
function handleQuery() {
  loading.value = true;
  getTimeProjectPage(queryParams)
    .then(({ data }) => {
      timeProjectList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开时间管理表单弹窗
 *
 * @param dicTypeId 时间管理ID
 */
function openDialog(
  id?: number,
  type?: TimeProjectTypeEnum,
  projectId?: number,
  addChildren: boolean = false
) {
  if (type === TimeProjectTypeEnum.PROJECT && !addChildren) {
    dialog.visible = true;
    if (id) {
      dialog.title = "修改时间管理";
      getTimeProjectForm(id).then(({ data }) => {
        Object.assign(formData, data);
      });
    } else {
      dialog.title = "新增时间管理";
    }
    return;
  }
  if (type === TimeProjectTypeEnum.PROJECT && addChildren) {
    openDialogItem(undefined, id);
  } else {
    openDialogItem(id, projectId);
  }
}

function openDialogItem(id?: number, projectId?: number) {
  dialogItem.visible = true;
  dialogItem.projectId = projectId as number;
  if (id) {
    dialogItem.title = "修改时间管理选项";
    getTimeProjectOptions(id).then(({ data }) => {
      Object.assign(formDataItem, data);
    });
  } else {
    dialogItem.title = "新增时间管理选项";
  }
}

/** 时间管理表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictTypeId = formData.id;
      if (dictTypeId) {
        updateTimeProject(dictTypeId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addTimeProject(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function handleSubmitItem() {
  dataItemFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loadingItem.value = false;
      const dictTypeId = formDataItem.id;
      formDataItem.projectId = dialogItem.projectId;
      if (dictTypeId) {
        updateTimeProjectOptions(dictTypeId, formDataItem)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialogItem();
            handleQuery();
          })
          .finally(() => (loadingItem.value = false));
      } else {
        addTimeProjectOptions(formDataItem)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialogItem();
            handleQuery();
          })
          .finally(() => (loadingItem.value = false));
      }
    }
  });
}

/** 关闭时间管理弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

function closeDialogItem() {
  dialogItem.visible = false;
  resetFormItem();
}

/**  重置时间管理表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

function resetFormItem() {
  dataItemFormRef.value.resetFields();
  dataItemFormRef.value.clearValidate();

  formDataItem.id = undefined;
  formDataItem.status = 1;
}

/** 删除时间管理 */
function handleDelete(dictTypeId?: number, type?: TimeProjectTypeEnum) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    if (type === TimeProjectTypeEnum.PROJECT) {
      deleteTimeProject(dictTypeId?.toString() ?? "").then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    } else {
      deleteTimeProjectOptions(dictTypeId?.toString() ?? "").then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      });
    }
  });
}

function handlePercentageInput(row: TimeProjectPageVO) {
  // if is not number
  if (isNaN(Number(row.percentage))) {
    row.percentage = 0;
  }
  row.percentage = Number(row.percentage);
  if (row.percentage < 0) {
    row.percentage = 0;
  } else if (row.percentage > 100) {
    row.percentage = 100;
  }
  // update row
  updateTimeProjectPercentage(row.id ?? 0, row).then(({ data }) => {
    if (data === null) {
      return;
    }
    // timeProjectList.value = timeProjectList.value?.map((item) => {
    //   if (item.id === data.id) {
    //     item.proportion = data.proportion;
    //     item.percentage = data.percentage;
    //   }
    //   return item;
    // });
  });
}

function handleProportionInput(row: TimeProjectPageVO) {
  // if is not number
  if (isNaN(Number(row.proportion))) {
    row.proportion = 0;
  }
  row.proportion = Number(row.proportion);
  if (row.proportion < 0) {
    row.proportion = 0;
  } else if (row.proportion > 100) {
    row.proportion = 100;
  }
  // update row
  updateTimeProjectProportion(row.id ?? 0, row).then(({ data }) => {
    if (data === null) {
      return;
    }
    // timeProjectList.value = timeProjectList.value?.map((item) => {
    //   if (item.id === data.id) {
    //     item.proportion = data.proportion;
    //     item.percentage = data.percentage;
    //   }
    //   return item;
    // });
  });
}

/**行点击事件 */
function onRowClick(row: TimeProjectPageVO) {
  selectedRowMenuId.value = row.id;
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

const selectedDictType = reactive({ typeCode: "", typeName: "" }); // 当前选中的时间管理

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.keywords"
            placeholder="时间管理名称/编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          type="success"
          @click="openDialog(undefined, TimeProjectTypeEnum.PROJECT)"
          ><i-ep-plus />新增</el-button
        >
        <!-- <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        :data="timeProjectList"
        highlight-current-row
        row-key="id"
        :expand-row-keys="['1']"
        @row-click="onRowClick"
        :tree-props="{
          children: 'children',
          hasChildren: 'hasChildren',
        }"
      >
        <el-table-column label="项目名称" prop="projectName" width="200">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.icon" />
            {{ scope.row.projectName }}
          </template>
        </el-table-column>
        <el-table-column
          label="选项名称"
          prop="itemName"
          align="center"
          width="100"
        />
        <el-table-column label="类型" :align="'center'" width="80">
          <template #default="scope">
            <el-tag
              v-if="scope.row.type === TimeProjectTypeEnum.PROJECT"
              type="warning"
              >项目</el-tag
            >
            <el-tag
              v-if="scope.row.type === TimeProjectTypeEnum.ITEM_PROJECT"
              type="success"
              >选项</el-tag
            >
            <el-tag
              v-if="scope.row.type === TimeProjectTypeEnum.DAY_ITEM_PROJECT"
              type="danger"
              >每天</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="状态" :align="'center'" width="100">
          <template #default="scope">
            <div v-if="scope.row.type !== TimeProjectTypeEnum.DAY_ITEM_PROJECT">
              <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
              <el-tag v-else type="info">禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="占比"
          prop="proportion"
          align="center"
          width="350"
        >
          <template #default="scope">
            <el-slider
              v-if="scope.row.type === TimeProjectTypeEnum.ITEM_PROJECT"
              v-model="scope.row.proportion"
              :proportion="scope.row.proportion"
              :disabled="scope.row.editing"
              @change="handleProportionInput(scope.row)"
              show-input
              :format-tooltip="(proportion: any) => `${proportion}%`"
            />
            <el-progress
              v-else-if="
                scope.row.type === TimeProjectTypeEnum.DAY_ITEM_PROJECT
              "
              :percentage="scope.row.proportionChange"
              :color="scope.row.proportionChange >= 100 ? '#13ce66' : '#20a0ff'"
              :format="(percentage: any) => `变化${percentage}%`"
            />
            <el-progress
              v-else
              :percentage="scope.row.proportion"
              :color="scope.row.proportion >= 100 ? '#13ce66' : '#20a0ff'"
              :format="(percentage: any) => `${percentage}%`"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="进度"
          prop="percentage"
          align="center"
          width="350"
        >
          <template #default="scope">
            <el-slider
              v-if="scope.row.type === TimeProjectTypeEnum.ITEM_PROJECT"
              v-model="scope.row.percentage"
              :percentage="scope.row.percentage"
              :disabled="scope.row.editing"
              @change="handlePercentageInput(scope.row)"
              show-input
              :format-tooltip="(percentage: any) => `${percentage}%`"
            />
            <el-progress
              v-else-if="
                scope.row.type === TimeProjectTypeEnum.DAY_ITEM_PROJECT
              "
              :percentage="scope.row.percentageChange"
              :color="scope.row.percentageChange >= 100 ? '#13ce66' : '#20a0ff'"
              :format="(percentage: any) => `变化${percentage}%`"
            />
            <el-progress
              v-else
              :percentage="scope.row.percentage"
              :color="scope.row.percentage >= 100 ? '#13ce66' : '#20a0ff'"
              :format="(percentage: any) => `${percentage}%`"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="开始时间"
          prop="beginTime"
          align="center"
          width="100"
          :formatter="
            (row) => {
              const date = new Date(row.beginTime);
              return isNaN(date.getTime())
                ? ''
                : date.toISOString().slice(0, 10);
            }
          "
        />
        <el-table-column
          label="结束时间"
          prop="endTime"
          align="center"
          width="100"
          :formatter="
            (row) => {
              const date = new Date(row.endTime);
              return isNaN(date.getTime())
                ? ''
                : date.toISOString().slice(0, 10);
            }
          "
        />
        <el-table-column
          label="创建时间"
          prop="createTime"
          align="center"
          width="100"
          :formatter="
            (row) => {
              const date = new Date(row.createTime);
              return isNaN(date.getTime())
                ? ''
                : date.toISOString().slice(0, 10);
            }
          "
        />
        <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.type == TimeProjectTypeEnum.PROJECT"
              type="primary"
              link
              size="small"
              @click.stop="
                openDialog(
                  scope.row.id,
                  scope.row.type,
                  scope.row.projectId,
                  true
                )
              "
            >
              <i-ep-plus />新增选项
            </el-button>
            <el-button
              v-if="
                scope.row.type == TimeProjectTypeEnum.PROJECT ||
                scope.row.type == TimeProjectTypeEnum.ITEM_PROJECT
              "
              type="primary"
              link
              size="small"
              @click.stop="
                openDialog(
                  scope.row.id,
                  scope.row.type,
                  scope.row.projectId,
                  false
                )
              "
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-if="
                scope.row.type == TimeProjectTypeEnum.PROJECT ||
                scope.row.type == TimeProjectTypeEnum.ITEM_PROJECT
              "
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id, scope.row.type)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="formData.projectName"
            placeholder="请输入项目名称"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker
            v-model="formData.beginTime"
            type="date"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="formData.endTime"
            type="date"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="时间管理备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- dialog item -->
    <el-dialog
      v-model="dialogItem.visible"
      :title="dialogItem.title"
      width="500px"
      @close="closeDialogItem"
    >
      <el-form
        ref="dataItemFormRef"
        :model="formDataItem"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="项目选项名称" prop="itemName">
          <el-input
            v-model="formDataItem.itemName"
            placeholder="请输入项目选项名称"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formDataItem.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formDataItem.remark"
            type="textarea"
            placeholder="项目选项备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitItem">确 定</el-button>
          <el-button @click="closeDialogItem">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
